package com.scau.RBAC.service.impl;

import com.scau.RBAC.model.entity.User;
import com.scau.RBAC.service.ExternalAuthService;
import com.scau.RBAC.exception.BusinessException;
import com.scau.RBAC.exception.ErrorCode;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地认证服务实现，作为默认的认证服务和降级服务
 */
public class LocalAuthServiceImpl implements ExternalAuthService {
    private static final Logger logger = LoggerFactory.getLogger(LocalAuthServiceImpl.class);
    private final ConcurrentHashMap<String, User> tokenStore = new ConcurrentHashMap<>();
    private final String serviceType = "LOCAL";

    @Override
    public User authenticate(String username, String password) {
        try {
            logger.info("使用本地认证服务进行用户认证: {}", username);

            // 这里是模拟实现，实际应用中应该调用本地用户DAO进行验证
            if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
                throw new BusinessException(ErrorCode.PARAM_ERROR, "用户名或密码不能为空");
            }

            // 模拟验证成功，创建用户对象
            User user = new User();
            user.setId(System.currentTimeMillis() + 20000);
            user.setUsername(username);
            user.setFullName(username + " (本地用户)");
            user.setEmail(username + "@local-system.com");
            user.setStatus(1);
            user.setLastLoginTime(LocalDateTime.now());
            user.setCreatedTime(LocalDateTime.now());

            logger.info("本地认证成功: {}", username);
            return user;
        } catch (BusinessException e) {
            logger.error("本地认证参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("本地认证服务错误", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "本地认证服务异常", e);
        }
    }

    @Override
    public User validateToken(String token) {
        User user = tokenStore.get(token);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "无效的本地认证令牌");
        }
        logger.info("本地令牌验证成功: {}", user.getUsername());
        return user;
    }

    @Override
    public String refreshToken(String oldToken) {
        User user = validateToken(oldToken);
        tokenStore.remove(oldToken);
        String newToken = "LOCAL-" + System.currentTimeMillis() + ":" + user.getId();
        tokenStore.put(newToken, user);
        logger.info("本地令牌刷新成功: {}", user.getUsername());
        return newToken;
    }

    @Override
    public void logout(Long userId) {
        // 清除相关令牌
        tokenStore.values().removeIf(user -> user.getId().equals(userId));
        logger.info("本地用户登出: {}", userId);
    }

    @Override
    public String getServiceType() {
        return serviceType;
    }

    @Override
    public boolean isAvailable() {
        // 本地服务永远可用，作为降级保障
        return true;
    }
}
